<?php

namespace app\admin\model\jeek\shop;

use app\common\model\Category;
use app\common\model\Dynamic;
use app\common\model\Follow;
use app\common\model\JeekMoneyLog;
use app\common\model\MoneyLog;
use app\common\model\OrderEvaluate;
use app\common\model\User;
use think\Db;
use think\Model;
use traits\model\SoftDelete;

/**
 * sku商品插件
 */
class SkuGoods extends Model
{
    use SoftDelete;


    // 表名
    protected $name = 'jeek_shop_sku_goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'price'
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    // 获取商品价格区间
    public function getPriceAttr($v, $d)
    {
        $specProduct = new SkuProduct();
        $list = $specProduct->where('goods_id', $d['id'])->order('price', 'asc')->column('price');
        $len = count($list);
        if ($len != 0) {
            if ($len == 1) return $list[0];
//        return $list[0] == $list[$len - 1] ? $list[0] : $list[0] . '~' . $list[$len - 1];
            return $list[0] == $list[$len - 1] ? $list[0] : $list[0];
        }
    }


    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getSite()
    {
        # vip折扣
        $vipdiscount = config('site.vip_discount') / 100;
        # 服务说明
        $service = config('site.service');
        return array($vipdiscount, $service);
    }


    /**
     * Account:列表查询
     * User: Ixiangang
     * Date: 2025/1/21
     * Time: 17:24
     */
    public function getListPage($where = [])
    {
        $this->getTermWhere($where, '');
        $field = $this->getField();
        $order = ['g.weigh' => 'desc'];
        $list = self::alias('g')
            ->join('jeek_level jl', 'jl.id = g.jeek_level_id', 'left')
            ->field($field)
            ->order($order)
            ->paginate()
            ->each(function ($item) use (&$extend, &$result) {
                # 查询咨询师分类
                $item->category_name = Category::where('id', 'in', $item->category_id)->column('name');
                return $item;
            });
        return $list;
    }

    /**
     * Account:查询咨询师
     * User: Ixiangang
     * Date: 2025/1/18
     * Time: 15:40
     */
    public function getList($where = [], $type = '', $limit = 10)
    {
        $row = $this->getTermWhere($where, $type);
        $field = $this->getField();
        $order = ['g.weigh' => 'desc'];
        $list = $row->alias('g')
            ->join('jeek_level jl', 'jl.id = g.jeek_level_id', 'left')
            ->field($field)
            ->order($order)
            ->limit($limit)
            ->select();
        array_map(function ($item) {
            # 查询咨询师分类
            $item->category_name = Category::where('id', 'in', $item->category_id)->column('name');
            return $item;
        }, $list);
        return $list;
    }

    /**
     * Account:字段整理
     * User: Ixiangang
     * Date: 2025/1/21
     * Time: 17:28
     */
    public function getField()
    {
        return "g.weigh,g.id,g.name,g.image,g.sales,g.workintime,g.category_id,jl.name as jeek_level_name";
    }

    /**
     * Account:列表查询条件
     * User: Ixiangang
     * Date: 2025/1/21
     * Time: 17:23
     */
    public function getTermWhere($where, $type)
    {
        return self::where(function ($query) use ($where, $type) {
            # 模糊查询咨询师姓名
            if (isset($where['keyword']) && $where['keyword']) {
                $query->whereLike('g.name', '%' . $where['keyword'] . '%');
            }
            # 根据分类查询咨询师
            if (isset($where['category_id']) && $where['category_id']) {
                $query->whereRaw("FIND_IN_SET(" . $where['category_id'] . ", category_id)");
            }
            # 查询我关注咨询师
            if (isset($where['goods_ids']) && $where['goods_ids']) {
                $query->where('g.id', 'in', $where['goods_ids']);
            }
            # 推荐列表
            if ($type == 'suggest') {
                $query->where('g.suggest', '1');
            }
            $query->where('g.status', '1');
            $query->where('g.deletetime IS NULL');
            $query->where('g.examine','2'); //审核通过
            $query->where('g.work', '1');
        });
    }


    /**
     * Account:获取咨询师信息
     * User: Ixiangang
     * Date: 2025/1/21
     * Time: 08:52
     */
    public function getInfo($goods_id, $user_id, $type = 'row')
    {
        if (!$goods_id || !$user_id) return false;
        $field = "g.id,g.name,g.image,g.sales,g.workintime,g.category_id,g.comments,g.details,g.video,g.honor_imgs,g.study,g.practicing_img,g.graduate_img,jl.name as jeek_level_name";
        $result = [];
        $list = self::alias('g')
            ->join('jeek_level jl', 'jl.id = g.jeek_level_id', 'left')
            ->where(function ($query) use ($goods_id) {
                $query->where('g.id', '=', $goods_id);
            })
            ->field($field)
            ->order(['g.id' => 'desc'])
            ->find();
        throw_validate_error(empty($list), "咨询师信息错误");
        $list->category_name = Category::where('id', 'in', $list->category_id)->column('name');
        if ($type == 'row') {
            # 查询用户是否是vio
            $list->vip = $uservip = User::where('id', $user_id)->value('vip');
            # 会员折扣价
            list($vipdiscount) = $this->getSite();
            $list->discount_price = $uservip == 1 ? bcmul($list->price, $vipdiscount, 2) : 0;

            # 服务规格
            $list->skus = $this->getSkuProduct($goods_id, $uservip);
            # 我的动态
            $dynamicInfo = (new Dynamic())->getListPage(['goods_id' => $goods_id]);
            $list->dynamic = !empty($dynamicInfo) ? ['dynamicCount' => $dynamicInfo->total(), 'dynamic_list' => !empty($dynamicInfo->items()) ? $dynamicInfo->items()[0] : ''] : '';
            # 我的评价
            $evaluateList = (new OrderEvaluate())->getList(['goods_id' => $goods_id], 3);
            $list->evaluate = !empty($evaluateList) ? ['evaluateCount' => (new OrderEvaluate())->getListPage(['goods_id' => $goods_id])->total(), 'evaluate_list' => $evaluateList] : '';
        }
        # 查询当前用户是否已关注
        $follow = Follow::where(['user_id' => $user_id, 'goods_id' => $list->id])->find();
        $list->is_follow = !empty($follow) ? 1 : 0; //1=已关注，0=未关注
        return $list;
    }


    /**
     * Account:查询服务
     * User: Ixiangang
     * Date: 2025/1/21
     * Time: 09:17
     */
    public function getSkuProduct($goods_id, $vip)
    {
        # 选择服务
        $product = SkuProduct::where(['goods_id' => $goods_id, 'status' => '1'])->select();
        $groups = [];
        $items = [];
        $specs = SkuSpec::with('skuItems')->where('goods_id', $goods_id)->select();
        $arr = collection($specs)->toArray();
        $itemKey = []; //商品使用
        foreach ($specs as $k => $v) {
            $groups[] = $v['name'];
            $i = [];
            foreach ($v['sku_items'] as $kk => $vv) {
                $i[] = $vv['name'];
                $itemKey[$vv['id']] = $vv['name'];
            }
            $items[] = $i;
        }
        # 服务时长说明
        list($vipdiscount, $service) = $this->getSite();
        $service_describe = [];
        foreach ($service as $k => $v) {
            if (in_array($k, $items[1])) {
                $service_describe[$k] = $v;
            }
        }
        # 查询规格
        $products = SkuProduct::where('goods_id', $goods_id)->field('id,price,goods_id,key')->select();
        $products = collection($products)->toArray();
        foreach ($products as $k => $v) {
            $keyArr = explode('_', $v['key']);
            $attr = [];
            foreach ($keyArr as $kk => $vv) {
                $attr[] = $itemKey[$vv];
            }
            # vip折扣 每个服务单价
            $products[$k]['discount_price'] = $vip == 1 ? bcmul($v['price'], $vipdiscount, 2) : 0; //会员折扣价
//            unset($products[$k]['key'], $products[$k]['id']);
            $products[$k]['attr'] = $attr;
        }
        //'groups' => $groups,
        $skus = ['items' => $items, 'products' => $products, 'service_describe' => $service_describe];
        return $skus;
    }



    /**
     * Account:记录资金流转
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 17:12
     */
    public static function money($money, $goods_id, $memo)
    {
        Db::startTrans();
        try {
            $goods = self::lock(true)->find($goods_id);
            if ($goods && $money != 0) {
                $before = $goods->money;
                $after = function_exists('bcadd') ? bcadd($goods->money, $money, 2) : $goods->money + $money;
                $goods->save(['money' => $after]);
                //写入日志
                $data = [
                    'goods_id' => $goods_id,
                    'money' => $money,
                    'before' => $before,
                    'after' => $after,
                    'memo' => $memo
                ];
                JeekMoneyLog::create($data);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }


}
